package com.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.constant.MsgConstant;
import com.blog.mapper.TravelMapper;
import com.blog.pojo.entity.Travel;
import com.blog.service.TravelService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TravelServiceImpl extends ServiceImpl<TravelMapper, Travel> implements TravelService {
    /**
     * 分页查询旅行图片
     * @param currentPage
     * @param pageSize
     * @param tag
     * @return
     */
    @Override
    public Page<Travel> getTravelPage(Integer currentPage, Integer pageSize, String tag) {
        // 1. 创建MP的Page对象设置分页条件
        Page page = new Page<>(currentPage, pageSize);

        // 2. 创建wrapper 设置其他的查询条件
        LambdaQueryWrapper<Travel> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(tag)) {
            wrapper.like(Travel::getTag, tag);
        }


        // 4. 进行分页查询，并返回数据
        try {
            return this.page(page, wrapper);
        } catch (Exception e) {
            log.error("分页查询旅行图片失败：", e);
            throw new RuntimeException(MsgConstant.TRAVEL_SELECT_ERROR);
        }
    }

    /**
     * 添加旅行图片
     * @param travel
     */
    @Override
    public void addTravel(Travel travel) {
        // 1. 没有什么设置的，直接添加
        try {
            this.save(travel);
        } catch (Exception e) {
            log.error("添加旅行图片失败：", e);
            throw new RuntimeException(MsgConstant.TRAVEL_ADD_ERROR);
        }
    }

    /**
     * 删除单个旅行图片
     * @param id
     */
    @Override
    public void deleteTravel(Long id) {
        // 1. 先检擦要删除的是否存在于数据库中
        if (this.getById(id) == null) {
            throw new RuntimeException(MsgConstant.TRAVEL_NO_EXISTS);
        }

        // 2. 进行删除
        try {
            this.removeById(id);
        } catch (Exception e) {
            log.error("删除单个旅行图片失败：", e);
            throw new RuntimeException(MsgConstant.TRAVEL_DELETE_ERRPR);
        }

    }

    /**
     * 批量删除旅行图片
     * @param ids
     */
    @Override
    public void deleteTravels(List<Long> ids) {
        // 1. 先检查要删除的是否都存在于数据库中
        LambdaQueryWrapper<Travel> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Travel::getId, ids);
        if (this.count(wrapper) != ids.size()) {
            throw new RuntimeException(MsgConstant.TRAVEL_NO_EXISTS);
        }

        // 2. 进行批量删除
        try {
            this.removeBatchByIds(ids);
        } catch (Exception e) {
            log.error("批量删除旅行图片失败：", e);
            throw new RuntimeException(MsgConstant.TRAVEL_DELETE_ERRPR);
        }


    }
}
